from db import Dd

class ACL():
    def __init__(self):
        self.db=Dd()

    # 获取权限
    def get_role(self,uid):
        sql="select node.name,node.auid,node.id from `node_user` inner join `user` on node_user.userid=user.id inner join `node` on node_user.node_id=node.id where user.id=%s" % uid
        list=[]
        dict={}
        data=self.db.get_all(sql)
        print(data)
        for i in data:
            dict['text']=i['name']
            dict[i['id']] = i
        for j in data:
            auid = j['auid']
            j['text'] = j['name']
            #  pid等于0，就是顶级，
            if auid == 0:
                # 直接加入列表
                list.append(j)
            else:
                #  查看父类是否有子类
                if 'children' not in dict[auid]:
                    dict[auid]['children'] = []
                dict[auid]['children'].append(j)
        print(list)
        return list
    # 添加权限
    def set_role(self,uid,roleid):
        sql="insert into `node_user` (node_id,userid) values (%s,%s)" % roleid,uid
        self.db.insert(sql)

    # 修改权限
    def update_role(self,uid,roleid):
        sql="delete  from `node_user` where userid=%s and roleid=%s" % (uid,roleid)
        self.db.delete(sql)
        sql = "insert into `node_user` (node_id,userid) values (%s,%s)" % roleid, uid
        self.db.insert(sql)
    # 删除单个权限
    def del_role(self,uid,roleid):
        sql = "delete  from `node_user` where userid=%s and node_id=%s" % (uid, roleid)
        self.db.delete(sql)


import redis
class RedisCon():
    def __init__(self):
        self.conn = redis.Redis(host='127.0.0.1', port=6379,db=1)
    #字符串存
    def str_set(self,key,value,time=0):
        if time == 0:
            return self.conn.set(key,value)
        else:
            #设置过期时间，单位是秒
            return self.conn.setex(key,time,value)

    #字符串读取
    def str_get(self,key):
        value = self.conn.get(key)
        if value:
            value = str(value,encoding='utf8')
        return value


    #删除
    def str_del(self,key):
        return self.conn.delete(key)


r = RedisCon()